package com.xq.tmall.agu.ferign;

import com.xq.tmall.entity.Stock;
import com.xq.tmall.entity.WebPage;
import com.xq.tmall.util.IpFerginUtil;
import com.xq.tmall.util.SpringContextUtil;
import com.xq.tmall.util.TradingDateUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;

/**
 * http://hq.sinajs.cn/list=%s
 * @author chenguoxiang
 * @create 2019-03-07 10:31
 **/
@Slf4j
public class FetchStockSpider extends AbstractFetchStockSpider<Stock> {

    private final String[] stockCodes;

    public FetchStockSpider(String[] stockCodes) {
        this.stockCodes = stockCodes;
        initSpiderConfig();
    }

    private void initSpiderConfig() {
        StringBuilder queryStr = new StringBuilder();
        IpFerginUtil ipFerginUtil = SpringContextUtil.getBean(IpFerginUtil.class);

        for (String code : stockCodes) {
            String resultCode = StockSpider.formatStockCode(code);
            if (null != resultCode) {
                queryStr.append(resultCode).append(",");
            }
        }

        String queryCode = queryStr.toString().replaceAll(",$", "");
        this.pageUrl = String.format("http://qt.gtimg.cn/q=%s", queryCode);
        this.timeOut = 8000;
        this.ignoreContentType = true;
        this.method = Connection.Method.GET;
        this.cookie = ipFerginUtil.getRedisCookies();
        this.useAgent = ipFerginUtil.getUseAgent();
        this.proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(
                        ipFerginUtil.getRedisIp(),
                        Integer.parseInt(ipFerginUtil.getRedisPort())
                )
        );
    }

    @Override
    protected List<Stock> parsePage(WebPage webPage) throws Exception {
        List<Stock> stockList = new ArrayList<>();
        String content = webPage.getDocument().text();
        List<String> rows = Arrays.asList(content.split(";"));

        for (String row : rows) {
            try {
                // 清理无效字符
                String cleanRow = row.replaceAll("v_.*=|\"", "");
                if (cleanRow.isEmpty()) continue;

                String[] item = cleanRow.split("~");
                if (item.length < 50) {
                    log.warn("Invalid data row: {}", cleanRow);
                    continue;
                }

                Stock stock = new Stock();
                stock.setName(item[1]);
                stock.setCode(item[2]);
                stock.setType(StockSpider.formatStockCode(item[2]).replaceAll("\\d", ""));
                stock.setPrice(Double.parseDouble(item[3]));
                stock.setYesterdayPrice(Double.parseDouble(item[4]));
                stock.setTotalValue(Double.parseDouble(item[5])); // 今开价格
                stock.setBvps(Double.parseDouble(item[6])); // 成交量
                stock.setFluctuate(Double.parseDouble(item[31])); // 涨跌额
                stock.setIndustry(item[32]); // 涨跌幅
                stock.setPes(Double.parseDouble(item[37])); // 成交额
                stock.setPb(Double.parseDouble(item[27])); // 换手率
                stock.setTodayMax(Double.parseDouble(item[33])); // 最高价
                stock.setTodayMin(Double.parseDouble(item[34])); // 最低价
                stock.setAmplitude(Double.parseDouble(item[43])); // 振幅
                stock.setPettm(Double.parseDouble(item[44])); // 流通市值
                stock.setDividend(Double.parseDouble(item[49])); // 量比
                stock.setRoe(Double.parseDouble(item[52])); // 市盈率（动）
                stock.setPriceDate(Long.valueOf(TradingDateUtil.getDateTime()));
                stock.setGoPettm(Double.parseDouble(item[72])); // 动态市盈率
                stockList.add(stock);
            } catch (Exception e) {
                log.error("Error parsing row: {}", row, e);
            }
        }
        return stockList;
    }
}
